package com.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.util.RandomValidateCodeUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
public class CodeController {

	@GetMapping(value = "/api/code")
	public void code(HttpServletRequest request, HttpServletResponse response) {
		try {
			// 设置相应类型,告诉浏览器输出的内容为图片
			response.setContentType("image/jpeg");
			// 设置响应头信息，告诉浏览器不要缓存此内容
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expire", 0);
			RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
			randomValidateCode.getRandcode(request, response);// 输出验证码图片方法
		} catch (Exception e) {
			log.error("获取验证码失败=>{}", e);
		}

	}

	/**
	 * 校验验证码
	 */
	@PostMapping(value = "/api/check-verify")
	public boolean checkVerify(@RequestParam String verifyInput, HttpSession session) {
		try {
			// 从session中获取随机数
			String inputStr = verifyInput;
			String random = (String) session.getAttribute(RandomValidateCodeUtil.RANDOMCODEKEY);
			if (random == null) {
				return false;
			}
			if (random.equals(inputStr)) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			log.error("验证码校验失败{}", e);
			return false;
		}
	}

}
